package ifi.p17.jarmanagement.control;

import ifi.p17.jarmanagement.model.Jar;
import ifi.p17.jarmanagement.model.Purchase;
import ifi.p17.jarmanagement.model.Revenue;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;

import android.os.Environment;
import android.util.Log;

public class FileProcess {

	public final static String HOME_DIR = Environment.getExternalStorageDirectory().getPath()+"/"; 
	public final static String APP_DIR = "GestionDepense/"; 
	public final static String SETTING_FILE = "curSetting.jr";
	public final static String REMAINING_FILE = "remainingMonth.jr";
	
	
	public static boolean writeToFile(String data, String folder, String filename, boolean append){		
		BufferedWriter bw = null;
		File file = null;
		try {
			// check folder null
			file = new File(HOME_DIR + APP_DIR + folder);
			if (!file.exists()) file.mkdirs();
			// write to file
			bw = new BufferedWriter(new FileWriter(file.getPath() + "/" +filename, append));
			bw.write(data);
			bw.newLine();
			bw.flush();
			bw.close();
		} catch (FileNotFoundException e) {
			Log.wtf("WRITE_FILE", "writeToFile");
			return false;
		} catch (IOException e) {
			Log.wtf("WRITE_FILE", "writeToFile");
			return false;
		}
		return true;
	}
	
	public static boolean fileExist(String filedir){
		File file = new File(filedir);
		return file.exists();
	}

	public static void loadSettingFromFile(Revenue revenu, Vector<Jar> jarList, Purchase cur_purchase) {
		BufferedReader br = null;
		StringTokenizer stok = null;
		try {
			br = new BufferedReader(new FileReader(HOME_DIR + APP_DIR + SETTING_FILE));
			/**
			 * amount remaining unit
			 * %jar1 current_depense
			 * ...
			 * **/
			// load revenu
			stok = new StringTokenizer(br.readLine());
			revenu.setAmount(Integer.parseInt(stok.nextToken()));
			revenu.setRemaining(Integer.parseInt(stok.nextToken()));
			revenu.setUnit(stok.nextToken());
			
			// load 6 jar
			for (int i=0; i<6; i++){
				stok = new StringTokenizer(br.readLine());
				jarList.get(i).setPercent(Integer.parseInt(stok.nextToken()));
				jarList.get(i).setCurrent(Integer.parseInt(stok.nextToken()));
			}
			
			String line = br.readLine();
			if (line!=null && line.length()>0){
//				StringTokenizer st = new StringTokenizer(line,"@");
//				String jarname = st.nextToken();
//				String time = st.nextToken();
//				int value = Integer.parseInt(st.nextToken());
//				String unit = st.nextToken();
//				String des = st.hasMoreElements() ? st.nextToken() : "" ;
//				cur_purchase.setNormalTypeInfo(jarname, time, value, unit ,des);
				cur_purchase.loadFromString(line);
			}
			
			br.close();
		} catch (FileNotFoundException e) {
			Log.wtf("READ_FILE", "loadSettingFromFile");
		} catch (IOException e) {
			Log.wtf("READ_FILE", "loadSettingFromFile");
		}
	}
	
	public static boolean writeCurrentSetting(Revenue revenu, Vector<Jar> jarList, Purchase cur_purchase){
		BufferedWriter bw = null;
		File file = null;
		try {
			// check folder null
			file = new File(HOME_DIR + APP_DIR);
			if (!file.exists()) file.mkdirs();
			// write to file
			bw = new BufferedWriter(new FileWriter(HOME_DIR + APP_DIR + SETTING_FILE));
			bw.write(Integer.toString(revenu.getAmount()) + " " + Integer.toString(revenu.getRemaining()) + " " + revenu.getUnit() + "\n");
			
			for (Jar jar : jarList){
				bw.write(Integer.toString(jar.getPercent()) + " " + Integer.toString(jar.getCurrent()));
				bw.write("\n");
			}
			
			if (cur_purchase.getType() == Purchase.TYPE_NORMAL) bw.write(cur_purchase.toString());
			bw.flush();
			bw.close();
		} catch (FileNotFoundException e) {
			Log.wtf("WRITE_FILE", "writeCurrentSetting");
			return false;
		} catch (IOException e) {
			Log.wtf("WRITE_FILE", "writeCurrentSetting");
			return false;
		}
		return true;
	}

	public static void loadPurchase(ArrayList<Purchase> list, String date) {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(HOME_DIR + APP_DIR + date));
//			LogErorr.out(HOME_DIR + APP_DIR + date + "--" + br.toString());
			// record: NEC@2012/4/22 15:20:23@200@Description
			String line = null;
			while ( (line=br.readLine()) !=null && line.length()!=0){
//				LogErorr.out(line);
//				StringTokenizer st = new StringTokenizer(line,"@");
//				String jarname = st.nextToken();
//				String time = st.nextToken();
//				int value = Integer.parseInt(st.nextToken());
//				String unit = st.nextToken();
//				String des = st.hasMoreElements() ? st.nextToken() : "" ;
				Purchase p = new Purchase();
				p.loadFromString(line);
				list.add(p);
			}
			br.close();
		} catch (FileNotFoundException e) {
			Log.wtf("READ_FILE", "loadPurchase");
		} catch (IOException e) {
			Log.wtf("READ_FILE", "loadPurchase");
		}
	}

	public static void getAllDayInMonth(String file, ArrayList<Purchase> dayinmonth) {
		// get all days availables
		for (int i=31; i>=1; i--){
			String fileday = file + "/" + Integer.toString(i);
			if (fileExist(HOME_DIR + APP_DIR + fileday)){
				// calculate all depense of this day
				int alldepense = 0;
				ArrayList<Purchase> thisday = new ArrayList<Purchase>();
				loadPurchase(thisday, fileday);
				for (Purchase pur : thisday){
//					LogErorr.out(pur.toString());
					alldepense += pur.getValue();
				}
				
				// add on list of day in monthS
				Purchase pur = new Purchase(Integer.toString(i), alldepense);
				dayinmonth.add(pur);
			}
		}
	}

	public static void getAllMonthInYear(String search_year, ArrayList<Purchase> monthInYear) {
		// get all month available
		for (int month=12; month>=1; month--){
			String filemonth = search_year + "/" + Integer.toString(month);
			if (fileExist(HOME_DIR + APP_DIR + filemonth)){
				// get revenu and remaining of this month
				int [] v = new int[2];
				readRemainingOfMonth(filemonth, v);
				
				// add on list of month in year
				Purchase pur = new Purchase(Integer.toString(month), v[0], v[1]);
				monthInYear.add(pur);
			}
		}
	}

	private static void readRemainingOfMonth(String filemonth, int [] v) {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(HOME_DIR + APP_DIR + filemonth + "/" + REMAINING_FILE));
			StringTokenizer stok = new StringTokenizer(br.readLine());
			v[0] = Integer.parseInt(stok.nextToken());
			v[1] = Integer.parseInt(stok.nextToken());
			br.close();
		} catch (FileNotFoundException e) {
			Log.wtf("READ_FILE", "readRemainingOfMonth");
		} catch (IOException e) {
			Log.wtf("READ_FILE", "readRemainingOfMonth");
		}
	}

	public static void loadAllPurchaseOfDate(String filedate, Vector<Purchase> list_of_day) {
		BufferedReader br = null;
		String line = null;
		try {
			br = new BufferedReader(new FileReader(HOME_DIR + APP_DIR + filedate));
			while ((line = br.readLine())!=null && line.length()>0){
				Purchase p = new Purchase();
				p.loadFromString(line);
				list_of_day.add(p);
			}
			br.close();
		} catch (FileNotFoundException e) {
			Log.wtf("READ_FILE", "loadAllPurchaseOfDate");
		} catch (IOException e) {
			Log.wtf("READ_FILE", "loadAllPurchaseOfDate");
		}
	}
	
	public static boolean writeAllPurchaseOfDate(String filedate, Vector<Purchase> list_of_day){
		BufferedWriter bw = null;
		try {
			// write to file
			bw = new BufferedWriter(new FileWriter(HOME_DIR + APP_DIR + filedate));

			for (Purchase pur : list_of_day){
				bw.write(pur.toString());
				bw.newLine();
			}
			bw.flush();
			bw.close();
		} catch (FileNotFoundException e) {
			Log.wtf("WRITE_FILE", "writeAllPurchaseOfDate");
			return false;
		} catch (IOException e) {
			Log.wtf("WRITE_FILE", "writeAllPurchaseOfDate");
			return false;
		}
		return true;
	}
}
